package com.classbook.violet.baigiang.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.classbook.violet.baigiang.model.ConnectionDetector;
import com.classbook.violet.baigiang.singleton.MyApplication;
import com.classbook.violet.baigiang.singleton.MySingleton;
import com.classbook.violet.baigiang.subject.SubjectParser;
import com.classbook.violet.baigiang7.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

public class LoadDataActivity extends Activity {

	private String URL = "http://classbook.vn/cbs/violet/download";

	private String PATH = Environment.getExternalStorageDirectory().getPath()
			+ "/EDC/Violet/";
	private SubjectParser mParser;

	private MyApplication myApp;
	private ProgressDialog pDialog;
	private ConnectionDetector mConnect;

	private int time_out = 0;
	private boolean result_update = false;
	private File root;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.loaddata);
		
		root = new File(PATH);
		if (!root.exists()){
			root.mkdirs();
		}

		myApp = (MyApplication) getApplication();
		myApp.customAppMethod();
		MySingleton.getInstance().customSingletonMethod();

		mConnect = new ConnectionDetector(this);
		if (mConnect.isConnectingToInternet()) {
			time_out = 0;
			new AsyncTaskUpdate().execute();
		} else {
			new AsyntaskParserXML().execute();
		}

	}

	public class AsyntaskParserXML extends AsyncTask<String, String, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LoadDataActivity.this);
			pDialog.setMessage("Reading data ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				InputStream is;
				if (new File(PATH + MySingleton.getInstance().xml_name).exists()) {
					is = new FileInputStream(PATH + MySingleton.getInstance().xml_name);
				} else {
					is = getResources().getAssets().open(MySingleton.getInstance().xml_name);
				}
				mParser = new SubjectParser(is);
				MySingleton.getInstance().mParser = mParser;
			} catch (Exception e) {
				Log.e("PARSER XML", e.toString());
				mParser.isParser = false;
			}
			Log.i("IsParserSuccess", "" + mParser.IsParserSuccess());
//			if (!mParser.IsParserSuccess()) {
//				AlertDialog.Builder al_connect = new AlertDialog.Builder(
//						LoadDataActivity.this);
//				al_connect.setTitle("Lỗi đọc XML");
//				al_connect.setMessage(mParser.error);
//
//				al_connect.setNegativeButton("OK",
//						new DialogInterface.OnClickListener() {
//							public void onClick(DialogInterface dialog, int id) {
//								new File(PATH + MySingleton.getInstance().xml_name).delete();
//								dialog.cancel();
//								new AsyntaskParserXML().execute();
//							}
//						});
//				al_connect.show();
//			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.cancel();
			Intent mIntent = new Intent(LoadDataActivity.this,
					MainActivity.class);
			startActivity(mIntent);
			finish();
		}
	}

	public class AsyncTaskUpdate extends AsyncTask<String, String, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LoadDataActivity.this);
			pDialog.setMessage("Đang cập nhật dữ liệu ... ");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			File new_file = new File(root, MySingleton.getInstance().xml_name);
			if (!new_file.exists()) {
				try {
					new_file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				URL url = new URL(URL + "?filename=" + MySingleton.getInstance().root_name + MySingleton.getInstance().xml_name);
				final HttpURLConnection urlConnection = (HttpURLConnection) url
						.openConnection();

				urlConnection.setRequestMethod("POST");
				urlConnection
						.addRequestProperty("authorization", "Violet@2013");
				urlConnection.connect();

				FileOutputStream fileOutput = new FileOutputStream(new_file);
				InputStream inputStream = urlConnection.getInputStream();
				byte[] buffer = new byte[1024];
				int bufferLength = 0;
				while ((bufferLength = (inputStream.read(buffer))) > 0) {
					fileOutput.write(buffer, 0, bufferLength);
					if (time_out > 3000) {
						Log.e("UPDATE", "FAIL");
						pDialog.cancel();
						Thread.interrupted();

					}
				}
				if (time_out < 3000) {
					Thread.interrupted();
					result_update = true;
				} else {
					new_file.delete();
					Thread.interrupted();
					result_update = false;
				}

			} catch (Exception e) {
				new_file.delete();
				Thread.interrupted();
				Log.e("ERROR UPDATE", e.toString());
				result_update = false;
			}

			return result_update;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.cancel();
			Log.v("UPDATE Result", "" + result);
			if (result) {
				Toast.makeText(LoadDataActivity.this, "Cập nhật thành công",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(LoadDataActivity.this, "Cập nhật thất bại",
						Toast.LENGTH_SHORT).show();
			}
			new AsyntaskParserXML().execute();
		}

	}

}
